﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using RBAC.Web.Mapper;
using RBAC.Web.Models;
using RBAC.Web.Service;
using RBAC.Web.Utilities;

namespace RBAC.Web.Controllers
{
    public class RoleController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListRole(int? page, string sort = "", string sortdir = "asc"
							, String RoleCodeSearch = ""
				        )    
		{
			//ถ้าตัวมันเป็นลูกของตัวอื่น ต้องทำการ clear ค่า TempData ของแม่ก่อน
				
			// end clear ค่า TempData

			ListRoleModel model = new ListRoleModel();
            /*GetAllResponseModel<RoleModel> temp = Search(new GetAllRoleRequestModel()
            {
									 RoleCode = RoleCodeSearch,
						                    Sort = sort,
					SortType = sortdir == "asc" ? sType.ASC : sType.DESC
            });
            model.ListItems = temp.List;*/
            
            return View(model);
        }

        [HttpPost]
        public ActionResult ListRole(string submitButton, string[] checkbox, ListRoleModel input)
        {
            if (ModelState.IsValid)
            {
               switch(submitButton) {
                   case "Search" :
                        input.ListItems = PrepareSearch(input);                      
                        break;
                   default :
                        break;
               }
            }
            return View(input);
        }

		public ActionResult EditRole(String RoleCode)
        {
            ServiceClient service = new ServiceClient();

            GetAllRoleRequestDto objGet = new GetAllRoleRequestDto()
            {
                EqPk = true,
				RoleCode = StringParser.GetValue<String>(RoleCode)
            };

            var list = service.GetAllRole(objGet);
			RoleModel resultModel = null;


			if (list.Data != null && list.Data.Count > 0)
			{
				RoleDto resultDto = list.Data[0];
				resultModel = RoleMapper.DtoToModel(resultDto);

				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
								
                resultModel.Permissions = PreparePermissions_PermissionSearch(resultModel.Id);
							}

						/**** ถ้ามีลูก gen  *****/
            //One-to-meny store parent's value to send to child
			if(resultModel != null)
			{
            TempData["RoleId"] = resultModel.Id;   

			 			
			TempData["RoleLookupField"] = resultModel.RoleCode;
						}
					
            //One-to-meny operaton message
            if (TempData["PermissionMessage"] != null && TempData["PermissionStatus"] != null)
            {
                ViewData["PermissionMessage"] = TempData["PermissionMessage"];
                ViewData["PermissionStatus"] = TempData["PermissionStatus"];
                if (TempData["PermissionId"] != null)
                    ViewData["PermissionId"] = TempData["PermissionId"];
            }
            /**** end *****/
						SetupRegisterViewModel(resultModel);
            return View(resultModel);
		}

		[HttpPost]
				public ActionResult Update(RoleModel inputModel)
				{
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.UpdateRole(RoleMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListRoleModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));
		
				 // เพิ่ม message แสดงในหน้าแม่
                TempData["RoleMessage"] = listDisplay.Message;
                TempData["RoleStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["RoleId"] = output.Data.Id;
                }
		                return View("ListRole", listDisplay);
		            }   
            else
            {
				//Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
								
                inputModel.Permissions = PreparePermissions_PermissionSearch(inputModel.Id);
				                SetupRegisterViewModel(inputModel);
                return View("EditRole", inputModel);
            }
			
		}

        public ActionResult Add()
        {
            RoleModel model = new RoleModel();
            SetupRegisterViewModel(model);

		
            return View("AddRole", model);
        }

        [HttpPost]
				 public ActionResult AddRole(RoleModel inputModel)
		        {
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.AddRole(RoleMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListRoleModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Add, output.Status));
          // เพิ่ม message แสดงในหน้าแม่
                TempData["RoleMessage"] = listDisplay.Message;
                TempData["RoleStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["RoleId"] = output.Data.Id;
                }
		                return View("ListRole", listDisplay);
		            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
           
        }

        [HttpPost]
        public string DeleteRoles(string[] RoleCheckbox)
        {
            ListRoleModel input = new ListRoleModel();
            if (ModelState.IsValid)
            {
                input = Delete(RoleCheckbox, input);
            }

            if(input.IsSuccessed.GetValueOrDefault(false))
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
        }

        [HttpPost]
        public String DeleteRoleById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            ServiceClient service = new ServiceClient();
            var output = service.DeleteRole(delList);

			//แสดง message ให้ class แม่
            TempData["RoleMessage"] = Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status);
            TempData["RoleStatus"] = output.Status;

            if (output.Status)
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
           
        }

        // Check does RoleCode exist
        [HttpPost]
        public JsonResult doesRoleCodeExist(string RoleCode, string Mode, string OldValue)
        {
			bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Trim().Equals(RoleCode.Trim(), StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
				var service = new ServiceClient();
                var exist = service.ExistRole(RoleCode).Data;
                return Json(!exist);
            }
            else
                return Json(true);
        }

		#region private methods

        private ListRoleModel Delete(string[] inputList, ListRoleModel input)
        {
            List<string> delList = new List<string>();
			var listDisplay = new ListRoleModel();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                ServiceClient service = new ServiceClient();
                var output = service.DeleteRole(delList);
                listDisplay = PrepareRetrunFromOperation(input, output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status));

				TempData["RoleMessage"] = listDisplay.Message;
                TempData["RoleStatus"] = output.Status;
            }

            listDisplay.ListItems = PrepareSearch(listDisplay);
            return listDisplay;
        }

        private List<RoleModel> PrepareSearch(ListRoleModel input)
        {

            GetAllRoleRequestModel searchInputs = new GetAllRoleRequestModel()
            {
									RoleCode = (input.RoleCodeSearch == null) ? ""  : input.RoleCodeSearch,
						
							Sort = "RoleCode",
				SortType = sType.ASC
			};
            var result = Search(searchInputs);
            return result.List;
        }

        private GetAllResponseModel<RoleModel> Search(GetAllRoleRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            GetAllRoleRequestDto gAllreq = new GetAllRoleRequestDto { 
		  							RoleCode = input.RoleCode,
		                   SortType = input.SortType.ToString(),
                 Sort = input.Sort
            };
            var response = service.GetAllRole(gAllreq);
            var result = new GetAllResponseModel<RoleModel>();
            result.List = new List<RoleModel>();
            if(response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (RoleDto responseDTO in response.Data)
                    {
                        RoleModel resultModel = null;
                        RoleDto tempDto = responseDTO;
                        resultModel = RoleMapper.DtoToModel(tempDto);
                        result.List.Add(resultModel);
                    }
                }
            }
            return result;
        }

		private ListRoleModel PrepareRetrunFromOperation(ListRoleModel listModel, RoleDto dto, bool status, string message)
		{
			if (status)
			{
				if (dto != null)
				{
					listModel.ListItems.Add(RoleMapper.DtoToModel(dto));
				}
			}
			listModel.Message = message;
			listModel.IsSuccessed = status;
			return listModel;

		}



		
		private GetAllResponseModel<PermissionModel> SearchPermissions_Permission(GetAllPermissionRequestModel input)
		{
			ServiceClient service = new ServiceClient();
			int roleId;
			int.TryParse(input.RoleId, out roleId);
			GetAllPermissionRequestDto gAllreq = new GetAllPermissionRequestDto
			{
				RoleId = roleId,
										PermissionName = input.PermissionName,

								Sort = input.Sort,
				SortType = input.SortType.ToString(),
			};
			var response = service.GetAllPermission(gAllreq);
			var result = new GetAllResponseModel<PermissionModel>();
			result.List = new List<PermissionModel>();
			if (response != null)
			{
				if (response.Data != null && response.Data.Count > 0)
				{
					foreach (PermissionDto responseDTO in response.Data)
					{
						PermissionModel resultModel = null;
						PermissionDto tempDto = responseDTO;
						resultModel = PermissionMapper.DtoToModel(tempDto);
						result.List.Add(resultModel);
					}
				}
			}
			return result;
		}

		private List<PermissionModel> PreparePermissions_PermissionSearch(int roleId)
		{
			ServiceClient service = new ServiceClient();
			GetAllPermissionRequestDto gAllreq = new GetAllPermissionRequestDto
			{
				RoleId = roleId
			};
			var response = service.GetAllPermission(gAllreq);
			var result = new GetAllResponseModel<PermissionModel>();
			result.List = new List<PermissionModel>();
			if (response != null)
			{
				if (response.Data != null && response.Data.Count > 0)
				{
					foreach (PermissionDto responseDTO in response.Data)
					{
						PermissionModel resultModel = null;
						PermissionDto tempDto = responseDTO;
						resultModel = PermissionMapper.DtoToModel(tempDto);
						result.List.Add(resultModel);
					}
				}
			}
			return result.List;
		}

		
		private void SetupRegisterViewModel(RoleModel model)
        {
            //เช็คว่ามี Attribute ที่เป็น DateTime ใน model หรือเปล่าถ้ามี + ปีไป 543 ถ้าปีเป็น ค.ศ.
            Utilities.Utilities.PrepareDateTimeProperity(model);
        }

		#endregion
    }
}
